//
//  XMStatusPictureView.swift
//  XMWeibo-Swift
//
//  Created by 育鑫 王 on 15/11/2.
//  Copyright © 2015年 育鑫 王. All rights reserved.
//

import UIKit
import SDWebImage

class XMStatusPictureView: UICollectionView {
    
    // MARK: - 属性
    ///  cell重用标识
    private let StatusPictureViewIdentifer = "StatusPictureViewIdentifer"
    
    /// 模型属性
    var status: XMStatus? {
        didSet{
            
            reloadData()
        }
    }
    
    override func sizeThatFits(size: CGSize) -> CGSize {
        return calcViewSize()
    }
    
    /// 根据微博模型,计算配图的尺寸
    func calcViewSize() -> CGSize {
        
        let itemSize = CGSize(width: 90, height: 90)
        
        // 设置itemSize
        layout.itemSize = itemSize
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0

        // 间距
        let margin : CGFloat = 10
        
        // 列数
        let column = 3
        
        // 根据模型的图片数量计算尺寸
        let count = status?.pictureURLs?.count ?? 0
        
        // 没有图片
        if count == 0 {
            return CGSizeZero
        }
        
        if count == 1 {
            // 获取图片url地址
            let urlString = status!.pictureURLs![0].absoluteString
            
            var size = CGSize(width: 150, height: 120)
            // 获取图片 , 有图片设置size为图片的size, 如果没有图片使用默认的
            if let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(urlString) {
                size = image.size
            }
            
            // 有些图片宽度很小
            if size.width < 40 {
                size.width = 40
            }
            
            layout.itemSize = size
            return size
        }
        
        layout.minimumLineSpacing = margin
        layout.minimumInteritemSpacing = margin
        
        // 4张图片
        if count == 4 {
            let width = itemSize.width * 2 + margin
            return CGSizeMake(width, width)
        }
        
        // 剩下2.3.5.6.7.8.9.
        // 计算行数: 公式: 行数 = (图片数量 + 列数 -1) / 列数
        let row = (count + column - 1) / column
        let width = (CGFloat(column) * itemSize.width) + CGFloat((column - 1)) * margin
        let height = (CGFloat(row) * itemSize.height) + CGFloat((row - 1)) * margin
        
        return CGSizeMake(width, height)
    }
    
    // 属性
    private var layout = UICollectionViewFlowLayout ()
    
    /// 构造函数
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    init() {
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        
        // 设置数据源
        dataSource = self
        
        // 注册cell
        registerClass(XMStatusPictureViewCell.self, forCellWithReuseIdentifier: StatusPictureViewIdentifer)
        
    }

}

// MARK: - 扩展 XMStatusPictureView ,实现 UICollectionViewDataSource协议
extension XMStatusPictureView: UICollectionViewDataSource {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return status?.pictureURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(StatusPictureViewIdentifer, forIndexPath: indexPath) as! XMStatusPictureViewCell
        
//        let url = status?.pic_urls?[indexPath.item]["thumbnail_pic"] as? String
        
        cell.imageURL = status?.pictureURLs?[indexPath.item]

        return cell
    }
    
}

// 自定义cell 显示图片
class XMStatusPictureViewCell: UICollectionViewCell {
    
    // MARK: - 属性
    var imageURL : NSURL? {
        didSet {
            // 设置图片
            iconView.sd_setImageWithURL(imageURL)
        }
    }
    
    // MARK: - 构造函数
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
         prepareUI()
    }
    
    private func prepareUI() {
        
        // 添加子控件
        addSubview(iconView)
    
        // 添加约束
        iconView.ff_Fill(contentView)
    }
    
    // MAEK: - 懒加载
    /// 图片
    private lazy var iconView = UIImageView()
    
}
